#include <iostream>
#include <string>
#include <cstdlib> // For getenv
#include <thread>
#include <chrono>
#include <nlohmann/json.hpp>
#include <curl/curl.h>

using json = nlohmann::json;

size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* userp) {
    size_t total_size = size * nmemb;
    userp->append((char*)contents, total_size);
    return total_size;
}

// 发送 HTTP 请求
json send_http_request(const std::string& url, const std::string& json_data, const std::string& api_key) {
    CURL* curl;
    CURLcode res;
    std::string read_buffer;

    curl = curl_easy_init();
    if(curl) {
        struct curl_slist* headers = nullptr;
        headers = curl_slist_append(headers, "Content-Type: application/json");
        headers = curl_slist_append(headers, ("Authorization: Bearer " + api_key).c_str());
 
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data.c_str());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &read_buffer);
        res = curl_easy_perform(curl);
    

        curl_easy_cleanup(curl);
        curl_slist_free_all(headers);
    }
    return json::parse(read_buffer);
}

// 主函数
std::string send_to_llm(std::string message) {
    // 初始化curl全局环境
    curl_global_init(CURL_GLOBAL_ALL);

    // 读取环境变量
    std::string deepseek_model_name =  std::getenv("deepseek_MODEL_NAME");
    std::string deepseek_api_key = std::getenv("deepseek_OPENAI_API_KEY");
    std::string deepseek_api_url = std::getenv("deepseek_OPENAI_API_URL");


    // 检查必要的环境变量
    if (deepseek_api_key.empty() || deepseek_api_url.empty()) {
        std::cerr << "Error: Required environment variables not set" << std::endl;
        std::cerr << "Please set deepseek_OPENAI_API_KEY and deepseek_OPENAI_API_URL" << std::endl;
        curl_global_cleanup();
        return "";
    }

    // 构造请求数据
    json request_body;
    request_body["model"] = deepseek_model_name;
    request_body["messages"] = {{{"role", "user"}, {"content", message}}, {{"role", "system"}, {"content", "you are a helpful assistant"}}};

    // 发送 HTTP 请求
    json response = send_http_request(deepseek_api_url + "/chat/completions", request_body.dump(), deepseek_api_key);
    std::string str_response=response.at("choices")[0].at("message").at("content").get<std::string>();


    curl_global_cleanup();
    return str_response;
}

int main() {
    std::string message = "你好";
    std::string response = send_to_llm(message);
    std::cout << response << std::endl;
    return 0;
}